import { _themeDetail, _commentList, _commentCount } from "../../../service/api";

Page({
  data: {
    id: null,
    theme: {},
    commentList: [],
    page: 1,
    size: 5,
    count: 0,
  },
  onLoad: function (options) {
    this.setData({ id: options.id });
    this.initData();
  },
  async onShow() {
    const { id, size, page } = this.data;
    const comment = await _commentList({ valueId: id, typeId: 1, size, page });
    this.setData({
      commentList: comment,
    });
  },
  async initData() {
    const { id } = this.data;
    let theme = await _themeDetail(id);
    let { count } = await _commentCount({ valueId: id, typeId: 1 });
    theme.content = theme.content.replace(/\<img/gi, '<img class="rich-img" ');
    this.setData({ theme: theme, count });
  },
  // 添加评论
  handleAddComment() {
    wx.navigateTo({ url: `/pages/theme/add_comment/add_comment?valueId=${this.data.id}&typeId=1` });
  },
  // 查看更多
  handleMore() {
    this.setData({
      page: parseInt(this.data.page) + 1,
    });
    if (this.data.page <= Math.ceil(this.data.count / 5)) {
      this.getCommentList();
    }
  },
  // 获取评论列表
  async getCommentList() {
    const { id, size, page } = this.data;
    const comment = await _commentList({ valueId: id, typeId: 1, size, page });
    console.log(comment);
    this.setData({
      commentList: [...this.data.commentList, ...comment],
    });
  },
  // 预览图片
  handleSeeImage(e) {
    const { url, index } = e.currentTarget.dataset;
    const { commentList } = this.data;
    let pics = commentList[index].pic_list.map((item) => item.pic_url);
    wx.previewImage({
      current: url,
      urls: pics,
    });
  },
});
